//获取应用实例
const app = getApp();
var shopCar,// 购物车, 
    _this,
    util = require('../../utils/util.js'),
    QQMapApi = 'https://apis.map.qq.com/ws/geocoder/v1/',
    qqmapsdk = 'HLFBZ-EGZK6-MVQS6-ESMKT-T2G37-GIB2U',
    monthsDays = [],
    times = ['00:00 - 03:00','03:00 - 06:00','06:00 - 09:00','09:00 - 12:00','12:00 - 15:00','15:00 - 18:00','18:00 - 21:00','21:00 - 00:00'];
var timeSecond = util.formatTime(new Date());
var date = timeSecond.split(" ")[0],
  year = parseInt(date.split("-")[0]),
  month = parseInt(date.split("-")[1]),
  day = parseInt(date.split("-")[2]),
  nowTime = 3, leapYear=false,
  timeNew = timeSecond.split(" ")[1];
// 计算是否是闰年
if (year % 400 == 0) {
  leapYear = true;
} else if (year % 4 == 0 && year % 100 != 0) {
  leapYear = true;
}
// 循环月份和日期
for (var a = month; a < 13; a++) {
  var today = 1, oneMonth = 31
  // 判断当前日期之后
  if (a == month) {
    today = day;
  }
  // 判断大小月
  if (a == 2) {
    // 判断是否是闰年
    if (leapYear && a == 2) {
      oneMonth = 29;
    } else {
      oneMonth = 28;
    }
  } else if (a == 1 || a == 3 || a == 5 || a == 7 || a == 8 || a == 10 || a == 12) {
    oneMonth = 31;
  } else if (a == 4 || a == 6 || a == 9 || a == 11) {
    oneMonth = 30;
  }
  for (var b = today; b < oneMonth + 1; b++) {
    var today = a + '月 ' + b + '日';
    monthsDays.push(today);
  }
}
// 获取当前时间
timeNew = parseInt(timeNew.split(":")[0])
//timeNew = 22
if (timeNew < 3) {
  nowTime = 1;
} else if (timeNew < 6) {
  nowTime = 2;
} else if (timeNew < 9) {
  nowTime = 3;
} else if (timeNew < 12) {
  nowTime = 4;
} else if (timeNew < 15) {
  nowTime = 5;
} else if (timeNew < 18) {
  nowTime = 6;
} else if (timeNew < 21) {
  nowTime = 7;
} else {
  nowTime = 8;
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userArea: null,      // 地址
    brandModelId: null,  // 机型
    shopCar: null,       // 购物车
    userBrandModel: null,// 机型
    nickName: null,      // 联系人
    phone: null,         // 联系电话
    date: null,          // 时间
    startTime: null,     // 开始时间
    endTime: null,       // 结束时间
    timeSecond:null,
    newMtServer: true,   // 防止订单重复提交
    serviceType: null,
    serviceTitle: null,// 标题
    controls: null,
    monthsDays: [],
    times: times,
    monthsDay: '请选择保养时间',
    time: '',
    //value: [0, nowTime],
    chooseDate: false,
    nowTime: 0,
    maintainType: [
      {
        image: 'icon_46_engine_',
        choose: true,
        name: '发动机',
        id: 7
      }, {
        image: 'icon_47_pressure_',
        choose: false,
        name: '液压件',
        id: 8
      }, {
        image: 'icon_48_device_',
        choose: false,
        name: '电器件',
        id: 4
      }, {
        image: 'icon_49_Chassis_',
        choose: false,
        name: '底盘件',
        id: 3
      }, {
        image: 'icon_50_get_',
        choose: false,
        name: '结构件',
        id: 10
      }, {
        image: 'icon_51_other_',
        choose: false,
        name: '其他',
        id: 9
      },
    ],
    categoryNameId: 7,
    buttonClicked: false,
    saveMapArea:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this;
    shopCar = false
    if (options.shopCar){
      shopCar = true;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    _this.mapCtx = wx.createMapContext('map');
    var res = wx.getSystemInfoSync()
    var left = (res.windowWidth / 2) - 35;
    var top = (res.windowHeight / 2) / 2 - 31;
    _this.setData({
      serviceTitle: app.globalData.Maintenance.serviceTitle,// 标题
      serviceType: app.globalData.Maintenance.serviceType,//类型
      // 地图地址
      userArea: {
        adcode:"",
        city:"",
        country:"",
        district:"",
        formattedAddresses: app.globalData.Maintenance.userArea.formattedAddresses,
        latitude: app.globalData.Maintenance.userArea.latitude,
        longitude: app.globalData.Maintenance.userArea.longitude,
        province:""
      },    // 地址
      // 原地址
      submitArea: app.globalData.Maintenance.userArea,
      // 储存地图地址
      saveMapArea: app.globalData.Maintenance.userArea,
      brandModelId: app.globalData.Maintenance.brandModelId,    // 机型
      shopCar: [],
      //shopCar: app.globalData.Maintenance.shopCar,    // 购物车
      userBrandModel: app.globalData.xieYouUserInfoRoot.userBrandModel,//机型
      nickName: app.globalData.xieYouUserInfo.nickname,     //联系人
      phone: app.globalData.xieYouUserInfo.phone,     //联系电话
      // 地图当前位置图标
      controls: [{
        id: 1,
        iconPath: "../../dist/images/map-icon.png",
        position: {
          left: left,
          top: top,
          width: 90,
          height: 75
        },
        clickable: false
      }]
    });
    // 获取购物车
    // if (shopCar){
    //   _this.setData({
    //     shopCar: app.globalData.Maintenance.shopCar
    //   })
    // }
    var serviceTitle = _this.data.serviceTitle
    /* 标题 */ 
    wx.setNavigationBarTitle({
      title: serviceTitle
    });
    // 维修时间插件 serviceType == '3' || serviceType == '0'  serviceType == '1' || serviceType == '2'
    // if (app.globalData.Maintenance.serviceType == '3' || app.globalData.Maintenance.serviceType == '0'){
    //   var timeSecond = util.formatTime(new Date());
    //   var time = timeSecond.split(" ")[0];
    //   // 设置end时间   
    //   year = parseInt(time.split("-")[0]) + 1;
    //   month = time.split("-")[1];
    //   day = time.split("-")[2];
    //   _this.setData({
    //     timeSecond: timeSecond,
    //     date: time,
    //     startTime: time,
    //     endTime: year + '-' + month + '-' + day
    //   })
    //   app.globalData.Maintenance.serviceDate = time;
    //   // 
    // } else if (app.globalData.Maintenance.serviceType == '1' || app.globalData.Maintenance.serviceType == '2'){
    //   // 初始化时间插件 保养
    //   _this.firstDate();
    // }
  },
  // 初始化时间选择
  firstDate: function () {
    var val = [0, nowTime], monthsDaysVal=0;
    // 判断 nowTime=8
    if (nowTime == 8){
      val = [1, nowTime-1];
      monthsDaysVal = 1;
    }
    _this.setData({
      monthsDays: monthsDays,
      times: times,
      //monthsDay: month + '月 ' + day + '日',
      //time: times[nowTime],
      value: val,
      year: year,
      nowTime: nowTime,
      monthsDaysVal: monthsDaysVal
    })
  },
  // 修改日期
  bindDateChange: function (e) {
    var val = e.detail.value;
    _this.setData({
      monthsDaysVal: val[0]
    })
    var monthsDaysVal = _this.data.monthsDaysVal,
        time = times[val[1]],
        monthsDay = monthsDays[monthsDaysVal];
    // 判断今天是否能选
    if (monthsDaysVal == 0 && nowTime == 8){
      monthsDay = monthsDays[1];
      _this.setData({
        monthsDay: monthsDays[1],
        value: [1, val[1]],
        monthsDaysVal: 1
      })
    }
    // 判断时间段是否能选
    else if (monthsDaysVal == 0 && val[1] < nowTime){
      var chooseTime = nowTime;
      if (nowTime == 8){
        chooseTime = chooseTime-1
      }
      time = times[chooseTime];
      _this.setData({
        monthsDay: monthsDay,
        time: times[chooseTime],
        value: [0, chooseTime]
      })
    }else{
      _this.setData({
        monthsDay: monthsDay,
        time: time,
        value: [val[0], val[1]]
      })
    }
    // // 拼凑 时间段
    // var timePs = monthsDay.split("月")
    // var monthNew = timePs[0];
    // var dayNew = timePs[1].split("日")[0];
    // app.globalData.Maintenance.serviceDate = year + '-' + monthNew + '-' + dayNew + ' 00:00';
  },
  // 维修 修改日期
  maintainBindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    _this.setData({
      date: e.detail.value,
      time: true
    })
    app.globalData.Maintenance.serviceDate = e.detail.value + ' 00:00';
  },
  // 打开关闭时间选择
  openCloseDateChoose:function(){
    var chooseDate = !_this.data.chooseDate,
    val = _this.data.value,
    valTime = val[1];
    if (valTime == 8){
      valTime = valTime-1
    }
    var monthsDay = monthsDays[val[0]],
    time = times[val[1]];
    var val = _this.data.value;
    _this.setData({
      chooseDate: chooseDate,
      monthsDay: monthsDay,
      time: time,
      value: val
    })
    if (!chooseDate){
      var monthChoose = monthsDay.split("月")[0],
        dayChoose = monthsDay.split(" ")[1];
      dayChoose = dayChoose.split("日")[0]
      // 年月日
      app.globalData.Maintenance.serviceDate = year + '-' + monthChoose + '-' + dayChoose + ' 00:00';
      // 开始结束时间
      app.globalData.Maintenance.serviceTimeBegin = time.split(' - ')[0] + ':00'
      app.globalData.Maintenance.serviceTimeEnd = time.split(' - ')[1] + ':00'
    }
    

  },
  // 修改电话
  servicePhone:function(e){
    console.log(e);
    var value = e.detail.value;
    _this.setData({
      phone: value
    })
  },
  // 修改姓名
  serviceName:function(e){
    console.log(e);
    var value = e.detail.value;
    _this.setData({
      nickName: value
    })
  },
  // 拖动map
  regionchange:function(){
    //_this.clickMap();
    console.log('regionchange 视野发生变化时触发')
    // 获取地图中心的经纬
    _this.getCenterLocation();  
  },
  // 获取地图中心地址
  getCenterLocation: function () {
    _this.mapCtx.getCenterLocation({
      success: function (res) {
        console.log('获取地图中心地址',res.longitude)
        console.log('获取地图中心地址',res.latitude)
        _this.showAddress(res.latitude, res.longitude);
      }
    })
  },
  // 腾讯地图逆向解析地址
  showAddress: function (latitude, longitude) {
    var qqMapApi = QQMapApi + "?location=" + latitude + ',' +
      longitude + "&key=" + qqmapsdk + "&get_poi=1";
    wx.request({
      url: qqMapApi,
      data: {},
      method: 'GET',
      success: (res) => {
        console.log('腾讯地图逆向解析地址',res);
        if (res.statusCode == 200 && res.data.status == 0){
          // 判断地址是否正确
          _this.judgeAddress(res.data.result);
          // _this.judgeAddress(res.data.result.ad_info);
          // console.log('地址逆袭', res);
        }
        // else{
        //   util.alertMsg('提示', '地图获取失败, 请稍后再试', function () {
        //     console.log('用户点击确定')
        //   }, function () {
        //     console.log('用户点击取消')
        //   });
        // }
      },
      fail:function(res){
        console.log('腾讯地图逆向解析地址-fail', res);
      },
      complete:function(res){
        console.log('腾讯地图逆向解析地址-complete', res);
      }
    })
  },
  // 判断地址是否正确
  judgeAddress: function (res) {
    // 储存传来的地址
    var mapArea = {};
    if (res.ad_info) {
      mapArea.latitude = res.ad_info.location.lat;// 经度
      mapArea.longitude = res.ad_info.location.lng; //维度
      mapArea.formattedAddresses = res.pois[0].address + ' ' + res.pois[0].title; //详细地址
      mapArea.adcode = res.ad_info.adcode  //code
      mapArea.city = res.ad_info.city         // 
      mapArea.country = res.ad_info.nation
      mapArea.district = res.ad_info.district
      mapArea.province = res.ad_info.province
    } else {
      mapArea.latitude = res.location ? res.location.lat : res.latitude;// 经度
      mapArea.longitude = res.location ? res.location.lng : res.longitude; //维度
      mapArea.formattedAddresses = res.address ? res.address : res.formattedAddresses; //详细地址
      mapArea.adcode = res.adcode  //code
      mapArea.city = res.city         // 
      mapArea.country = res.nation
      mapArea.district = res.district
      mapArea.province = res.province
    }
    _this.setData({
      saveMapArea: mapArea
    })
    // 所在地区code
    var adcode = _this.data.submitArea.adcode;
    var submitArea = _this.data.submitArea
    // 之前的地址 —— 省市区
    var area = submitArea.district
    var detailAddress = res.address;
    if (!mapArea.formattedAddresses) {
      // 超过区域，重新选择地区
      util.alertMsg('提示', '请选择地址', function () {
        console.log('用户点击确定')
        return;
      }, function () {
        console.log('用户点击取消')
        return;
      });
      return false;
    }
    if (mapArea.adcode){
      if (adcode != mapArea.adcode) {
        // 超过区域，重新选择地区
        var aa = '超出' + submitArea.district + '请重新选择';
        util.alertMsg('提示', aa, function () {
          console.log('用户点击确定')
          return;
        }, function () {
          console.log('用户点击取消')
          return;
        });
        return false;
      } else {
        console.log('_this.data.submitArea==', _this.data.submitArea.formattedAddresses)
        return true;
      }
    }
  },
  // 验证信息
  verifyService:function(){
    var _this =this;
    wx.showLoading({
      title: '加载中',
    })
    // Map选择的的地址
    var saveMapArea = _this.data.saveMapArea;
    if (!saveMapArea.formattedAddresses){
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('提示', '请选择维修地址', function () {
        console.log('用户点击确定')
        return;
      }, function () {
        console.log('用户点击取消')
        return;
      });
      return;
    }
    // 提交需要验证的code
    var submitArea = _this.data.submitArea
    // 之前的地址 —— 省市区
    var saveMapAreaCode = saveMapArea.adcode
    var submitAreaCode = submitArea.adcode;
    if (saveMapAreaCode != submitAreaCode) {
      // 取消加载中
      wx.hideLoading();
      // 超过区域，重新选择地区
      var aa = '超出' + submitArea.district + '请重新选择';
      util.alertMsg('提示', aa, function () {
        console.log('用户点击确定')
        return;
      }, function () {
        console.log('用户点击取消')
        return;
      });
      return;
    }
    if (_this.data.phone == null || _this.data.phone == '') {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请输入您的联系电话', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
      /*验证手机号*/
    }
    var isPhone = false;
    util.testPhone(_this.data.phone, function (rs) {
      if (rs) {
        isPhone = true;
      } else {
        isPhone = false;
      }
    });
    if (!isPhone) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告','请输入正确的手机号码',function(){
        console.log('用户点击确定')
      },function(){
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.nickName == null || _this.data.nickName == '') {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请填写您的名字', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.submitArea.formattedAddresses == null) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择您的详细地址', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.brandModelId == null) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择你的机型', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    if (_this.data.serviceType == '' || _this.data.serviceType == null) {
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('警告', '请选择你的维修类型', function () {
        console.log('用户点击确定')
      }, function () {
        console.log('用户点击取消')
      });
      return;
    }
    // app数据更新 时间 姓名 电话 详细地址
    _this.applyServiceWx();
  },
  applyServiceWx:function(){
    var data = {
      latitude: _this.data.saveMapArea.latitude,// 经度
      longitude: _this.data.saveMapArea.longitude, //维度
      country: _this.data.saveMapArea.country,//国家
      province: _this.data.saveMapArea.province,  //省
      city: _this.data.saveMapArea.city,//城市
      area: _this.data.saveMapArea.district, //district 地区
      areaCode: _this.data.saveMapArea.adcode, // 地区areaCode
      detailAddress: _this.data.saveMapArea.formattedAddresses, //详细地址

      userCode: app.globalData.xieYouUserInfo.code,//  userCode
      contact: _this.data.nickName,  //contact联系人
      contactPhone: _this.data.phone, //contactPhone 联系电话
      //repairmanCode: payload.repairmanCode,//维修工编码 支付后在匹配维修师

      serviceType: _this.data.serviceType, //服务类型
      //categoryNameId: categoryNameId,// 故障类型
      //description: payload.description, //description 描述
      serviceDate: app.globalData.Maintenance.serviceDate,//serviceDate 服务日期
      brandId: app.globalData.xieYouUserInfoRoot.userBrandModel.brand.id,
      brandModelId: app.globalData.xieYouUserInfoRoot.userBrandModel.brandModel.id,
      shopCar: _this.data.shopCar
    };
    //serviceType == '3' || serviceType == '0'  serviceType == '1' || serviceType == '2'
    if (_this.data.serviceType == '1' || _this.data.serviceType == '2'){
      data.servicePlaceType = 0;
      data.serviceTimeBegin = app.globalData.Maintenance.serviceTimeBegin;// 保养开始时间
      data.serviceTimeEnd = app.globalData.Maintenance.serviceTimeEnd;      // 保养结束时间
    }
    if (_this.data.serviceType == '0' || _this.data.serviceType == '3'){
      data.categoryNameId = _this.data.categoryNameId;// 故障类型
    }
    if (_this.data.newMtServer) {
      _this.setData({
        newMtServer: false// 防止重复提交
      });
      app.applyService(data, function (rs) {
        if (rs) {
          if (rs.status == 'success') {
            // 取消加载中
            wx.hideLoading();
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 1500,
              mask: true,
              success: function(){
                // // 核算订单
                // 更新首页订单
                app.refreshIndex();
                //跳转 mtOrderTabPage
                // 保养订单 
                //serviceType == '3' || serviceType == '0'  serviceType == '1' || serviceType == '2'
                if (rs.data.serviceType == '1' || rs.data.serviceType == '2'){
                  if (!_this.data.buttonClicked) {
                    util.buttonClicked(_this);
                    wx.navigateTo({
                      url: '/pages/service-detail/service-detail?id=' + rs.data.id + '&type=ing' + '&tab=1'
                    })
                    
                  }
                }
                // 维修订单进入详情页
                if (rs.data.serviceType == '3' || rs.data.serviceType == '0'){
                  if (!_this.data.buttonClicked) {
                    util.buttonClicked(_this);
                    wx.navigateTo({
                      url: '/pages/choose-repairman/choose-repairman?id=' + rs.data.id + '&type=ing' + '&tab=1'
                    })
                  }
                }
                
                // wx.navigateBack({
                //   delta: pages.length - 1
                // })
                // // 更新首页订单
                // app.refreshIndex();
                // //跳转 mtOrderTabPage
                // wx.navigateTo({
                //   url: '../service-detail/service-detail?id=' + rs.data.id + '&type=ing' + '&tab=1'
                // })
              }
            })
            // $state.go('mt.userOrderDetail', { id: rs.data.id }, true);
          } else {
            // 取消加载中
            wx.hideLoading();
            util.alertMsg('错误', rs.message, function () {
              console.log('用户点击确定')
            }, function () {
              console.log('用户点击取消')
            });
          }
        } else {
          util.alertMsg('错误', '网络异常, 请稍后再试', function () {
            console.log('用户点击确定')
          }, function () {
            console.log('用户点击取消')
          });
        }
      });
    }else{
      // 取消加载中
      wx.hideLoading();
      util.alertMsg('提示', '请勿重复提交订单', function () {
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.reLaunch({
            url:'/pages/index/index'
          })
        }
      }, function () {
        if (!_this.data.buttonClicked) {
          util.buttonClicked(_this);
          wx.reLaunch({
            url: '/pages/index/index'
          })
        }
      });
    }
  },
  searchArea(){
    var saveMapArea = _this.data.submitArea
    if (!_this.data.buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: '/pages/search-address/search-address',
      })
    }
  },
  // 维修 选择类型
  chooseMaintainType(e){
    var index = e.currentTarget.dataset.index,
    maintainType = _this.data.maintainType;
    for (var i = 0; i < maintainType.length;i++){
      maintainType[i].choose = false;
    } 
    maintainType[index].choose = true;
    _this.setData({
      maintainType: maintainType,
      categoryNameId: maintainType[index].id
    })
  },
  // 保养修改地址
  chooseAddress:function(){
    var saveMapArea = _this.data.saveMapArea;
    if (_this.judgeAddress(saveMapArea)){
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];  //上一个页面
      prevPage.setData({
        saveMapArea: saveMapArea
      })
      wx.navigateBack({
        delta: 1
      })
    }
  }
})

